<script setup lang="ts">
import { Button, Space } from 'ant-design-vue'
import { inject, onMounted } from 'vue'
import { isEmpty } from 'lodash-es'
import { ModalContext, modalInjectionKey } from '@idmy/core'

defineOptions({ name: 'ModalButton' })

defineProps({
	cancel: { type: Boolean, default: true },
	cancelText: { type: String, default: '取消' },
	ok: { type: Boolean, default: true },
	okText: { type: String, default: '确定' },
})

const emit = defineEmits({
	cancel: (inModal: boolean) => true,
	ok: (inModal: boolean) => true,
	mounted: (inModal: boolean, modal: ModalContext) => true,
})

const modal = inject<ModalContext>(modalInjectionKey, {} as any)

const inModal = () => !isEmpty(modal)

const onCancel = () => {
	modal?.close?.()
	emit('cancel', inModal())
}

const loading = defineModel<boolean>('loading', { type: Boolean, default: false })
const okDisabled = defineModel<boolean>('okDisabled', { type: Boolean, default: false })
const onOk = async () => {
	emit('ok', inModal())
}

onMounted(() => emit('mounted', inModal(), modal))
</script>

<template>
	<Space class="df jce">
		<Button @click="onCancel" v-if="cancel" :disabled="loading || modal?.closing || modal?.lock">
			{{ cancelText }}
		</Button>
		<slot v-bind="modal" :inModal="inModal()">
			<Button v-if="ok" type="primary" html-type="submit" :disabled="loading || modal?.closing || okDisabled" @click="onOk" :loading="loading">
				{{ okText }}
			</Button>
		</slot>
	</Space>
</template>
